package com.zhang.service.impl;

import com.zhang.dao.CategoryMapper;
import com.zhang.entity.Category;
import com.zhang.service.CategoryService;
import com.zhang.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class CategoryServiceImpl implements CategoryService {
    @Override
    public List<Category> selectAll() {
        List<Category> cateList = new ArrayList<>();
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            CategoryMapper dao = sqlSession.getMapper(CategoryMapper.class);
            cateList = dao.selectAll();
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return cateList;
    }

    @Override
    public List<Category> selectNum(int id) {
        SqlSession sqlSession = null;
        List<Category> list = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            CategoryMapper dao = sqlSession.getMapper(CategoryMapper.class);
            list = dao.selectNum(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return list;
    }

    @Override
    public Category selectById(int id) {
        SqlSession sqlSession = null;
        Category category = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            CategoryMapper dao = sqlSession.getMapper(CategoryMapper.class);
            category = dao.selectById(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return category;
    }
}
